package org.wzy.xmlg_backend.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wzy.xmlg_backend.entity.Result;
import org.wzy.xmlg_backend.entity.Student;
import org.wzy.xmlg_backend.service.IStudentService;
import org.wzy.xmlg_backend.service.IClassService;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@Tag(name = "StudentController", description = "学员管理")
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IClassService classService;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.access-path}")
    private String accessPath;

    // 头像上传
    @PostMapping("/upload")
    @Operation(summary = "上传学员头像")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择上传文件");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + fileExt;

            // 创建存储目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 保存文件
            File dest = new File(dir, fileName);
            file.transferTo(dest);

            // 返回完整访问路径
            String fullAccessPath = accessPath + fileName;
            return Result.success(fullAccessPath);
        } catch (IOException e) {
            return Result.fail("头像上传失败: " + e.getMessage());
        }
    }

    // 分页查询
    @GetMapping("/page")
    @Operation(summary = "分页查询学员")
    public Result<Page<Student>> pageStudents(
            @Parameter(description = "学员姓名") @RequestParam(required = false) String name,
            @Parameter(description = "性别") @RequestParam(required = false) String gender,
            @Parameter(description = "班级ID") @RequestParam(required = false) Integer classId,
            @Parameter(description = "状态(1-在读,0-已离开)") @RequestParam(required = false) Integer status,
            @Parameter(description = "所在地") @RequestParam(required = false) String location,
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "5") Integer size) {

        Page<Student> page = new Page<>(current, size);
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(name)) {
            queryWrapper.like(Student::getName, name);
        }
        if (StringUtils.hasText(gender)) {
            queryWrapper.eq(Student::getGender, gender);
        }
        if (classId != null) {
            queryWrapper.eq(Student::getClassId, classId);
        }
        if (status != null) {
            queryWrapper.eq(Student::getStatus, status);
        }
        if (StringUtils.hasText(location)) {
            queryWrapper.like(Student::getLocation, location);
        }

        queryWrapper.orderByDesc(Student::getUpdateTime);

        Page<Student> result = studentService.page(page, queryWrapper);
        // 处理头像路径为完整URL
        processAvatarUrls(result.getRecords());
        return Result.success(result);
    }

    // 根据ID查询
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取学员")
    public Result<Student> getStudentById(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        if (student != null) {
            processAvatarUrl(student);
            return Result.success(student);
        } else {
            return Result.fail("学员不存在");
        }
    }

    // 创建学员
    @PostMapping
    @Operation(summary = "创建学员")
    public Result<Student> createStudent(@RequestBody Student student) {
        // 验证班级是否存在
        if (student.getClassId() != null && classService.getById(student.getClassId()) == null) {
            return Result.fail("班级不存在");
        }

        // 设置默认状态为在读(1)
        if (student.getStatus() == null) {
            student.setStatus(1);
        }

        // 处理头像路径
        if (student.getAvatar() != null && !student.getAvatar().isEmpty()) {
            // 确保存储的是相对路径
            student.setAvatar(convertToRelativePath(student.getAvatar()));
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        student.setCreateTime(now);
        student.setUpdateTime(now);

        boolean success = studentService.save(student);
        if (success) {
            // 返回前处理为完整路径
            processAvatarUrl(student);
            return Result.success(student);
        } else {
            return Result.fail("创建学员失败");
        }
    }

    // 更新学员
    @PutMapping("/{id}")
    @Operation(summary = "更新学员")
    public Result<Student> updateStudent(@PathVariable Integer id, @RequestBody Student student) {
        Student existingStudent = studentService.getById(id);
        if (existingStudent == null) {
            return Result.fail("学员不存在");
        }

        // 验证班级是否存在
        if (student.getClassId() != null && classService.getById(student.getClassId()) == null) {
            return Result.fail("班级不存在");
        }

        student.setId(id);
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(existingStudent.getCreateTime());

        // 处理头像路径
        if (student.getAvatar() != null && !student.getAvatar().isEmpty()) {
            // 确保存储的是相对路径
            student.setAvatar(convertToRelativePath(student.getAvatar()));
        } else {
            // 保留原有头像
            student.setAvatar(existingStudent.getAvatar());
        }

        boolean success = studentService.updateById(student);
        if (success) {
            // 返回前处理为完整路径
            processAvatarUrl(student);
            return Result.success(student);
        } else {
            return Result.fail("更新学员失败");
        }
    }

    // 删除学员
    @DeleteMapping("/{id}")
    @Operation(summary = "删除学员")
    public Result<Void> deleteStudent(@PathVariable Integer id) {
        boolean exists = studentService.getById(id) != null;
        if (!exists) {
            return Result.fail("学员不存在");
        }

        boolean success = studentService.removeById(id);
        if (success) {
            return Result.success();
        } else {
            return Result.fail("删除学员失败");
        }
    }

    // 批量删除学员
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除学员")
    public Result<Void> deleteStudentsBatch(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.fail("请选择要删除的学员");
        }

        boolean success = studentService.removeByIds(ids);
        if (success) {
            return Result.success();
        } else {
            return Result.fail("批量删除学员失败");
        }
    }

    // 导入学员数据
    @PostMapping("/import")
    @Operation(summary = "导入学员数据")
    public Result<String> importStudents(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择上传文件");
        }

        try {
            InputStream inputStream = file.getInputStream();
            List<Student> studentList = EasyExcel.read(inputStream)
                    .head(Student.class)
                    .sheet()
                    .doReadSync();

            // 处理导入数据
            for (Student student : studentList) {
                // 设置默认状态
                if (student.getStatus() == null) {
                    student.setStatus(1);
                }

                // 处理头像路径
                if (student.getAvatar() != null && !student.getAvatar().startsWith("http")) {
                    student.setAvatar(convertToRelativePath(student.getAvatar()));
                }

                // 设置时间
                LocalDateTime now = LocalDateTime.now();
                student.setCreateTime(now);
                student.setUpdateTime(now);
            }

            studentService.saveBatch(studentList);
            return Result.success("导入成功，共导入 " + studentList.size() + " 条数据");
        } catch (Exception e) {
            return Result.fail("导入失败: " + e.getMessage());
        }
    }

    // 导出学员数据
    @GetMapping("/export")
    @Operation(summary = "导出学员数据")
    public void exportStudents(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=students.xlsx");

            List<Student> studentList = studentService.list();
            // 处理头像路径为完整URL
            processAvatarUrls(studentList);

            EasyExcel.write(response.getOutputStream(), Student.class)
                    .sheet("学员数据")
                    .doWrite(studentList);
        } catch (IOException e) {
            throw new RuntimeException("导出失败", e);
        }
    }

    // 处理单个学员的头像URL
    private void processAvatarUrl(Student student) {
        if (student.getAvatar() == null || student.getAvatar().isEmpty()) {
            return;
        }

        // 已经是完整URL则直接返回
        if (student.getAvatar().startsWith("http")) {
            return;
        }

        // 避免重复添加accessPath
        if (!student.getAvatar().startsWith(accessPath)) {
            student.setAvatar(accessPath + student.getAvatar());
        }
    }

    // 处理多个学员的头像URL
    private void processAvatarUrls(List<Student> students) {
        if (students == null) return;
        for (Student student : students) {
            processAvatarUrl(student);
        }
    }

    // 将完整路径转换为相对路径存储
    private String convertToRelativePath(String fullPath) {
        if (fullPath == null || fullPath.isEmpty()) return fullPath;

        // 如果包含访问路径前缀，则移除
        if (fullPath.startsWith(accessPath)) {
            return fullPath.substring(accessPath.length());
        }

        // 如果是其他完整路径，保留原样
        if (fullPath.startsWith("http")) {
            return fullPath;
        }

        return fullPath;
    }
}